﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DNA
{
    class DnaIndexReversed
    {
        private DnaIndex _index = null;
        private StringBuilder _builder = null; 

        internal string _ReverseString(string nucl)
        {
            _builder.Remove(0, _builder.Length);
            _builder.EnsureCapacity(nucl.Length);
            int x = nucl.Length;
            for (int i = 0; i < nucl.Length; i++)
            {
                char c = nucl[--x];
                _builder.Insert(i, c);
            }

            return _builder.ToString();
        }

        public DnaIndexReversed(DnaIndex index) 
            : this()
        {
            List<string> nucleotides = index.getAll();
            StringBuilder builder = new StringBuilder();

            foreach (string nucl in nucleotides)
            {
                string reversed = _ReverseString(nucl);
                _index.Add(reversed);
            }
        }

        public DnaIndexReversed()
        {
            _index = new DnaIndex();
            _builder = new StringBuilder();
        }

        public DnaIndexReversed(StringReader reader) : this()
        {
            string line = null;
            while ((line = reader.ReadLine()) != null)
                _index.Add(_ReverseString(line));
        }

        public DnaIndexReversed(string data)
            : this(new StringReader(data))
        {
        }

        public DnaIndexReversed(List<string> list) : this()
        {
            foreach (var nucl in list)
                _index.Add(nucl);
        }

        public void Add(string nucl)
        {
            _index.Add(_ReverseString(nucl));
        }

        public bool Contains(string nucl)
        {
            return _index.Contains(_ReverseString(nucl));
        }
        
        public List<string> findAllEndingWith(string polimer)
        {
            List<string> found = _index.findAllStartingWith(_ReverseString(polimer));
            List<string> reversed = new List<string>();

            foreach (var nucl in found)
                reversed.Add(_ReverseString(nucl));

            reversed.Sort();
            return reversed;
        }

        public List<string> getAll(string polimer)
        {
            return findAllEndingWith("");
        }

        public void Remove(string polimer)
        {
            _index.Remove(_ReverseString(polimer));
        }
    }
}
